// 1. 安装路由模块
// yarn add vue-router
// 2. 导入模块
import Vue from 'vue'
import VueRouter from 'vue-router'
import {getToken} from '../utils/localData'
// 3. 注册路由组件 <router-view> 和 <router-link>




Vue.use(VueRouter)

// 4. 路由映射关系
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import User from '../views/User.vue'
import UserEdit from '../views/UserEdit.vue'
import Article from '../views/Article.vue'
import UserFollow from '../views/UserFollow.vue'
import UserStar from '../views/UserStar.vue'
import UserComment from '../views/UserComment.vue'
import Comment from '../views/Comment.vue'
import Category from '../views/Category.vue'
import Search from '../views/Search.vue'
import cuowu from '../views/404/cuowu.vue'


const routes = [
  { path: '/' ,component: Home },
  { path: '/home' ,component: Home },
  { path: '/login' ,component: Login,name:'Login'},
  { path: '/register' ,component: Register },
  // { path: '/user' ,component: User },
  // { path: '/userEdit' ,component: UserEdit },
  { path: '/article/:id', component: Article },
  // { path: '/user_follow', component: UserFollow },
  // { path: '/user_star', component: UserStar },
  // { path: '/user_comment', component: UserComment },
  { path: '/comment/:id', component: Comment },
{ path: '/category', component: Category },
{ path: '/search', component: Search},
  // 🧐直接在配置路由信息的时候，写上需要检查哪些页面
  { meta: { check: true }, path: '/user', component: User },
  { meta: { check: true }, path: '/userEdit', component: UserEdit },
  { meta: { check: true }, path: '/user_follow', component: UserFollow },
  { meta: { check: true }, path: '/user_star', component: UserStar },
  { meta: { check: true }, path: '/user_comment', component: UserComment },
]

// 5. new 一个路由实例
const router = new VueRouter({
  // routes? 有问号的提示，说明是 VueRouter 的提示
  routes,
  mode: 'history'
})
// 路由守卫
// to 目标地址（去哪里）
// from 跳转前地址（从哪来）
// next 是否放行（是一个函数）
router.beforeEach((to, from, next) => {
  // cnonsole.log('to',to);
  // console.log('from',from);
  // next()

  // 部分页面访问的时候需要确认是否有token
  if (to.meta.check) {
    console.log(to.path,"需要检查")
    // 如果有成功获取到token
   
    if(getToken()){
      // 放行
      next();
    }else{
      // 没有 token就跳转到登录页
      next({path :'/login'});
    }
  }
 else{
    next()
  }
})

// 6.1 导出路由实例
export default router